package jp.co.redfox.archclub.utility.datas;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import jp.co.redfox.archclub.poker.GameException;
import jp.co.redfox.archclub.poker.GameFile;

public abstract class AbstractFixedLengthData {

    protected int idlength;
    protected int[] lengths;
    protected AbstractFixedLengthData(int idLength, int... lengths){
        this.idlength = idLength;
        this.lengths = lengths;
    }
    
    protected String[] dataContents;
    public void loadFixedLengthData(String id){
        if ( id == null)
            return;
        
        if(lengths.length == 0)
            throw new Error("壊れてる");
        
        dataContents = new String[lengths.length];
        
        
        try (BufferedReader in = new BufferedReader(new FileReader(getDataFile()))){
            
            String line = null;
            int idlength = this.idlength;
            
            if(idlength == 0)
                throw new Error("壊れてる");
            
            while ((line = in.readLine()) != null)
                if(id.equals(line.substring(0,idlength)))
                    break;
            
            if(line == null)
                return;

            int sumLength = idlength;
            for(int cnt = 0; cnt < lengths.length; cnt++)
                try{
                    dataContents[cnt] = line.substring(sumLength, lengths[cnt]);
                }catch(StringIndexOutOfBoundsException e){
                    System.out.println();   // TODO
                    break;
                }catch(ArrayIndexOutOfBoundsException e){
                    break;
                }
            
        } catch (IOException e) {
            throw new GameException("ファイル処理中にエラーが発生しました。", e);
        }
    }
    
    protected abstract GameFile getDataFile();

    protected File createDefaultFile() {
        GameFile file = getDataFile();
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException ioe) {
                throw new GameException("ファイルを作成できませんでした。" , ioe);
            }
        }
        return file;
    }
}
